package com.crnn.smart.utils.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    public static ApplicationContext get() {
        if (null == context) {
            throw new UnsupportedOperationException("ApplicationContext not ready!");
        }
        return context;
    }

    public static Object getBean(String beanName) {
        try {
            return get().getBean(beanName);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            return get().getBean(clazz);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        try {
            return get().getBean(beanName, clazz);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (null == SpringContextHolder.context) {
            SpringContextHolder.context = applicationContext;
        }
    }
}
